﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Text.RegularExpressions;

namespace Utilities
{
    /// <summary>
    /// File 的摘要说明。
    /// </summary>
    public class WebUtility
    {


        #region 创建文件夹
        public static void createDir(string dirPath)
        {
            // 判断路径是否已经存在，不存在则创建文件夹
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
        }
        #endregion

        #region 创建文件
        /// <summary>
        /// 根据路径创建建文件
        /// </summary>
        /// <param name="fileContent">string</param>
        /// <param name="filePath">like "D:\1\" 以"\"结束</param>
        /// <param name="fileName">1.htm</param>
        public static void CreateFile(string filePath, string fileName, string fileContent)
        {
            // 判断路径是否存在
            string fullFilePath = Path.Combine(filePath, fileName);
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            // 判断文件是否存在
            if (File.Exists(fullFilePath))
            {
                File.Delete(fullFilePath);
            }

            // 创建并打开文件 做写入操作
            FileStream fs = File.OpenWrite(fullFilePath);
            try
            {
                // 定义Buffer
                Byte[] buffer;
                buffer = Encoding.Default.GetBytes(fileContent);

                // Buffer长度
                int bufferLen = buffer.Length;

                // BUFFER_SIZE
                int bufferSize = 10;

                int bufferLoop = bufferLen % bufferSize == 0 ? (bufferLen / bufferSize) : ((bufferLen / bufferSize) + 1);

                // int BytesRead
                int bufferReadLen;

                for (int i = 0; i < bufferLoop; i++)
                {
                    if (i != (bufferLoop - 1))
                    {
                        bufferReadLen = bufferSize;
                    }
                    else
                    {
                        if (bufferLen % bufferSize == 0)
                            bufferReadLen = bufferSize;
                        else
                            bufferReadLen = bufferLen % bufferSize;
                    }

                    fs.Write(buffer, i * bufferSize, bufferReadLen);
                }
            }
            finally
            {
                fs.Close();
            }
        }
        #endregion

        #region 根据URL获取返回的String流
        /// <summary>
        /// 该方法用于根据URL获取返回的String流
        /// </summary>
        /// <param name="url">目标网址</param>
        /// <returns>获取的目标服务器返回HTML字符</returns>
        public static string GetWebsiteCode(string url)
        {
            HttpWebRequest myRq = (HttpWebRequest)HttpWebRequest.Create(url);
            myRq.AllowAutoRedirect = true;
            myRq.Timeout = 30000;
            StreamReader sr = null;
            Stream mystr = null;

            StringBuilder Html = new StringBuilder();
            try
            {
                HttpWebResponse myRp = (HttpWebResponse)myRq.GetResponse();
                mystr = myRp.GetResponseStream();
                sr = new StreamReader(mystr, Encoding.Default);
                while (sr.Peek() != -1)
                {
                    Html.Append(sr.ReadToEnd());
                }
            }
            catch
            {
                return "";
            }
            // return Html.ToString().Replace("\n","").Replace("\r","").Trim();
            return Html.ToString().Trim();
        }
        #endregion

        #region 根据url和发送的信息返回string 流
        /// <summary>
        /// 根据url和发送的信息返回string 流
        /// </summary>
        /// <param name="url">目标网址</param>
        /// <param name="data">发送的信息</param>
        /// <returns>获取的目标服务器返回HTML字符</returns>
        public static string GetWebsiteCode(string url, string data)
        {
            string Data1 = data;
            Encoding encoding = Encoding.Default;
            byte[] Data = encoding.GetBytes(Data1);
            // 设置httpWebRequest属性
            HttpWebRequest myRq = (HttpWebRequest)HttpWebRequest.Create(url);
            myRq.AllowAutoRedirect = true;
            myRq.Timeout = 100000;
            myRq.Method = "Post";
            myRq.ContentLength = Data.Length;
            myRq.ContentType = "application/x-www-form-urlencoded";
            CookieContainer myc = new CookieContainer();
            myRq.CookieContainer = myc;
            // 设置输出流并发送到指定网址
            Stream outStream = myRq.GetRequestStream();
            outStream.Write(Data, 0, Data.Length);
            outStream.Close();
            // 利用httpWebResponse得到传回信息
            HttpWebResponse myRp = (HttpWebResponse)myRq.GetResponse();
            StringBuilder Html = new StringBuilder();
            Stream myStr = myRp.GetResponseStream();
            StreamReader sr = new StreamReader(myStr, Encoding.Default);
            while (sr.Peek() != -1)
            {
                Html.Append(sr.ReadLine() + "\r\n");
            }
            return Html.ToString();
        }
        #endregion

        #region 得到IP地址
        public static string GetRequestIP()
        {
            try
            {
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                        return System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                    else
                        return "";
                }
                else
                {
                    if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                        return System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                    else
                        return "";
                }
            }
            catch
            {
                throw;
            }
        }
        #endregion


        /// <summary>
        /// 返回文本内容给客户端
        /// </summary>
        /// <param name="obj"></param>
        public static void ResponseText(object obj)
        {
            HttpResponse Response = HttpContext.Current.Response;
            Response.Clear();

            Response.ContentType = "text/plain";
            Response.Charset = "utf-8";

            Response.Write(obj.ToString());
            Response.End();

        }


        public static void PageNoCache()
        {
            HttpResponse Response = HttpContext.Current.Response;
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
        }



        /// <summary>
        /// 返回网站目录
        /// </summary>
        /// <returns></returns>
        public static string webPath
        {
            get
            {
                string path = System.Web.HttpContext.Current.Request.ApplicationPath;
                if (!path.EndsWith("/"))
                    path += "/";
                return path;
            }
        }

        public static string WebHost
        {
            get { return System.Web.HttpContext.Current.Request.Url.Authority; }
        }

        public static string RelativePath
        {
            get { return System.Web.HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath; }
        }


        #region 下载文件
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="content">内容</param>
        /// <param name="encoding">编码</param>
        /// <param name="doucmentType">文档类型</param>
        /// <param name="openModel">打开模式</param>
        public static void WebOutFile(string fileName, string content, Encoding encoding, DoucmentType doucmentType, FileOpenModel openModel)
        {
            string contentType = "";
            if (encoding == null)
                encoding = System.Text.Encoding.UTF8;

            switch (doucmentType)
            {
                case DoucmentType.Excel:
                    contentType = "application/ms-excel";
                    break;
                case DoucmentType.Html:
                    contentType = "application/ms-html";
                    break;
                case DoucmentType.Txt:
                    contentType = "application/ms-txt";
                    break;
                case DoucmentType.Word:
                    contentType = "application/ms-word ";
                    break;
                default:
                    throw new NotImplementedException(string.Format("{0} 类型未知！", contentType));

            }

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(string.Format("<meta http-equiv=\"Content-Type\" content=\"text/html\" charset=\"{0}\"/>", encoding.WebName));
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = encoding.WebName;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("{0};filename={1}", openModel == FileOpenModel.Attachment ? "attachment" : "online", fileName));
            HttpContext.Current.Response.ContentEncoding = encoding;
            HttpContext.Current.Response.ContentType = contentType;
            HttpContext.Current.Response.Write(content);
            HttpContext.Current.Response.End();

        }


        public static void WebOutFile(string fileName, Encoding encoding, DoucmentType doucmentType, FileOpenModel openModel)
        {
            string contentType = "";
            if (encoding == null)
                encoding = System.Text.Encoding.UTF8;

            switch (doucmentType)
            {
                case DoucmentType.Excel:
                    contentType = "application/ms-excel";
                    break;
                case DoucmentType.Html:
                    contentType = "application/ms-html";
                    break;
                case DoucmentType.Txt:
                    contentType = "application/ms-txt";
                    break;
                case DoucmentType.Word:
                    contentType = "application/ms-word ";
                    break;
                default:
                    throw new NotImplementedException(string.Format("{0} 类型未知！", contentType));

            }
            FileInfo fileInfo = new FileInfo(fileName);

            HttpContext.Current.Response.Clear();
            //            HttpContext.Current.Response.Write(string.Format("<meta http-equiv='Content-Type'; content='text/html';charset='{0}'>", encoding.WebName));
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = encoding.WebName;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("{0};filename={1}", openModel == FileOpenModel.Attachment ? "attachment" : "online", fileInfo.Name));
            HttpContext.Current.Response.ContentEncoding = encoding;
            HttpContext.Current.Response.ContentType = contentType;
            HttpContext.Current.Response.WriteFile(fileName);
            HttpContext.Current.Response.End();

        }
        #endregion

        public static string GetControlString(Control control)
        {
            return GetControlString(control, false);
        }


        public static string GetControlString(Control control, bool isVerifyForm)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ZH-CN", true);
            using (System.IO.StringWriter writer = new System.IO.StringWriter(culture))
            {
                control.EnableViewState = false;
                if (isVerifyForm)
                {

                    Page page = new Page();
                    HtmlForm form = new HtmlForm();

                    page.EnableEventValidation = false;
                    page.DesignerInitialize();
                    page.Controls.Add(form);
                    form.Controls.Add(control);
                    page.RenderControl(new HtmlTextWriter(writer));
                }
                else
                {
                    control.RenderControl(new HtmlTextWriter(writer));
                }

                return writer.ToString();
            }
        }

        //以前的
        public static string CreateExcelToText(DataTable data)
        {
            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符  
            StringBuilder sb = new StringBuilder();
            int index = 0;
            int columnCount = data.Columns.Count;

            foreach (DataColumn column in data.Columns)
            {
                sb.Append(column.Caption);
                if (index == columnCount)
                    sb.Append("\n");
                else
                    sb.Append("\t");
                index++;
            }
            foreach (DataRow row in data.Rows)
            {
                for (int i = 0; i < columnCount; i++)
                {
                    sb.Append(row[i].ToString());
                    if (i == columnCount)
                        sb.Append("\n");
                    else
                        sb.Append("\t");
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 通过url获取文件完整的名称
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetWebFileFullName(string url)
        {
            if (string.IsNullOrEmpty(url))
                return "";
            Match match = Regex.Match(url, @"[^\/|\\]+$");
            if (match.Success)
                return match.Value;
            return "";
        }

        public static string GetFileName(string url)
        {
            string fileName = GetWebFileFullName(url);
            if (fileName.Length == 0)
                return "";
            int endIndex = fileName.LastIndexOf('.');
            if (endIndex < 0)
                return fileName;
            return fileName.Substring(0, endIndex);
        }


        public static Control FindControl(Control control, string controlID)
        {
            Control namingContainer = control;
            Control control3 = null;
            if (control != control.Page)
            {
                while ((control3 == null) && (namingContainer != control.Page))
                {
                    namingContainer = namingContainer.NamingContainer;
                    if (namingContainer == null)
                    {
                        throw new HttpException(string.Format("{0}无法找到控件对象{1}", control.ID, controlID));
                    }
                    control3 = namingContainer.FindControl(controlID);
                }
                return control3;
            }
            return control.FindControl(controlID);
        }

        /**/
        /// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;

                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”，估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];     //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;     //代理中的内容 非IP，取IP 
                    }

                }


                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];



                if (string.IsNullOrEmpty(result))
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (string.IsNullOrEmpty(result))
                    result = HttpContext.Current.Request.UserHostAddress;

                return result;
            }
        }

        /**/
        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string input)
        {
            if (input == null || input == string.Empty || input.Length < 7 || input.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(input);
        }

    }





    //文档类型
    public enum DoucmentType
    {
        Txt,
        Excel,
        Word,
        Html
    }

    //文件打开方式打开方式
    public enum FileOpenModel
    {
        /// <summary>
        /// 附件下载
        /// </summary>
        Attachment,
        /// <summary>
        /// 在线打开
        /// </summary>
        Online,
    }
}
